<?php

namespace app\api\controller;

use addons\third\library\Service;
use app\common\library\Auth;
use app\common\model\SelfMessage;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\score\Task;
use app\common\model\Address;
use fast\Random;
use think\Validate;
use think\Db;
use addons\third\Third;
use fast\Http;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'login_wx'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);

        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            Task::execute_task(2, $data['userinfo']['id']);
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            Task::execute_task(2, $data['userinfo']['id']);
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        //$email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        /*if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }*/
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        //推荐人信息
        $extends = [];
        
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, '', $mobile, $extends);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            Task::execute_task(2, $data['userinfo']['id']);
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        //nickname, avatar, gender, birthday, province, city, county, 
        $user = $this->auth->getUser();
        $data = $this->request->post();
        unset($data['token']);

        //print_r($data);
        $key = array_keys($data)[0];
        if(!in_array($key, array('nickname', 'avatar', 'gender', 'birthday'))){
            $this->error('参数有误');
        }
        //die;

        /*$nickname = $this->request->request('nickname');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $gender = $this->request->request('gender/d', 0);
        $birthday = $this->request->request('birthday', '', 'trim,strip_tags,htmlspecialchars');
        $province = $this->request->request('province/d', 0);
        $city = $this->request->request('city/d', 0);
        $county = $this->request->request('county/d', 0);

        $user->nickname = $nickname;
        $user->avatar = $avatar;
        $user->gender = $gender;
        $user->birthday = $birthday;
        $user->province = $province;
        $user->city = $city;
        $user->county = $county;
*/

        $user->save($data);
        $this->success('操作成功');
    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $email   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号码格式有误'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('手机号码已存在'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('短信验证码有误'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success('操作成功');
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                Task::execute_task(2, $data['userinfo']['id']);
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    /*
     * 获取登陆用户信息
     */
    public function getUserInfo(){
        $user_id = $this->auth->getUserinfo()['id'];
        $where['id'] = $user_id;
        $field = 'id, nickname, email, mobile, avatar, gender, money, score, invi_code, birthday, province,  city, county, top_id, maxsigns';
        $userInfo = \app\common\model\User::where($where)->field($field)->find();
        $avatar = $userInfo['avatar'];
        $service_name = $this->request->domain();
        if($userInfo['avatar'] && strstr($userInfo['avatar'], 'http') === false && 
            strstr($userInfo['avatar'], 'data:image') === false){
            $userInfo['avatar'] = $service_name.$avatar;
        }

        $userInfo['message_num'] = SelfMessage::where([
            'to_user_id' => $user_id,
            'status' => 0,
        ])->count();

        $this->success('用户信息', $userInfo);
    }

    /*
     * 关注/取消关注
     */
    public function attention(){
        $user_id = $this->auth->getUserinfo()['id'];
        $to_user_id = input('to_user_id/d', 0);

        if($user_id == $to_user_id){
            $this->error('不能关注自己');
        }
        $data['user_id'] = $user_id;
        $data['to_user_id'] = $to_user_id;

        $attention = Db::name('self_attention')->where($data)->find();
        if($attention){
            $is_success = Db::name('self_attention')->where(array('id'=>$attention['id']))->delete();
        }else{
            $data['createtime'] = time();
            $is_success = Db::name('self_attention')->insertGetId($data);   
            if($is_success){
                Task::execute_task(14, $this->auth->id);
            } 
        }

        
        if($is_success !== false){
            $this->success('操作成功');  
        }else{
            $this->error('操作失败');    
        }
    }

    /*
     * 收藏
     */
    public function favorite(){
        $user_id = $this->auth->getUserinfo()['id'];
        $type = input('type/d', 0);
        $data_id = input('data_id/d', 0);

        $data['user_id'] = $user_id;
        $data['type'] = $type;
        $data['data_id'] = $data_id;
        $data['createtime'] = time();

        $is_success = Db::name('self_favorite')->insertGetId($data);
        if($is_success){
            $this->success('操作成功');  
        }else{
            $this->error('操作失败');    
        }
    }

    /*
     * 地址列表
     */
    public function addressList(){
        $user_id = $this->auth->getUserinfo()['id'];
        $addresslist = Address::where(array('user_id'=>$user_id))->order('is_default desc,id desc')->select();

        $this->success('地址列表', $addresslist);
    }

    /*
     * 根据id获取某条地址
     */
    public function getAddressById(){
        $user_id = $this->auth->getUserinfo()['id'];
        $id = input('id/d', 0);
        $address = Address::where(array('user_id'=>$user_id, 'id'=>$id))->find();

        $this->success('地址详情', $address);   
    }
    /*
     * 添加修改地址
     */
    public function editAddress(){
        $user_id = $this->auth->getUserinfo()['id'];
        $data = $this->request->post();
        unset($data['token']);

        $data['user_id'] = $user_id;
        $data['createtime'] = time();

        if(isset($data['share_from'])) unset($data['share_from']);

        if(!isset($data['telephone']) || !preg_match('/^1[3|4|5|6|7|8|9]\d{9}$/', $data['telephone'])){
            $this->error("手机号码填写有误");
        }

        if(isset($data['id'])){
            $address = Address::where(array('user_id'=>$user_id, 'id'=>$data['id']))->find();
            if(!$address){
                $this->error("未找到地址");
            }
            $is_success = $address->allowField(true)->save($data);
        }else{
            $is_success = (new Address)->allowField(true)->create($data);
        }

        if($is_success !== false){
            $this->success('操作成功');   
        }else{
            $this->error('操作失败');
        }

    }

    /*
     * 我的粉丝
     */
    public function fansList(){
        $user_id = $this->auth->getUserinfo()['id'];
        $field = 'atte.id, atte.user_id, atte.createtime, u.nickname,u.avatar';
        $where['atte.to_user_id'] = $user_id; 
        $fans = Db::name('self_attention')->alias('atte')
            ->join('hb_user u', 'atte.user_id = u.id')
            ->field($field)
            ->where($where)
            ->paginate();
        $this->success('我的粉丝', $fans);   
    }

    /*
     * 我的关注
     */
    public function attentionList(){
        $user_id = $this->auth->getUserinfo()['id'];
        $field = 'atte.id, atte.to_user_id, atte.createtime, u.nickname,u.avatar';
        $where['atte.user_id'] = $user_id; 
        $fans = Db::name('self_attention')->alias('atte')
            ->join('hb_user u', 'atte.to_user_id = u.id')
            ->field($field)
            ->where($where)
            ->paginate();
        $this->success('我的关注', $fans);  
    }

    /*
     * 看单历史记录
     */
    public function historyList(){
        $user_id = $this->auth->getUserinfo()['id'];
        $where['user_id'] = $user_id;
        
        $field = 'id, createtime, ad_id';
        $his_list = Db::name('self_history')
            ->field($field)
            ->where($where)
            ->order('createtime DESC')
            ->paginate()
            ->each(function($item){
                $item['createtime_text'] = date('Y-m-d H:i', $item['createtime']);
                $ad = \app\common\model\ads\Ad::field('id,title,type,category,files')->find($item['ad_id']);
                $ad->file_list = $ad->file_list;
                $item['info'] = $ad;
                return $item;
            })
            ->toArray();
        $this->success('我的看单', $his_list);
    }

    /**
     * 登录
     */
    public function login_wx()
    {
        $config = config('wxapp');
        
        $code = $this->request->post("code");
        $rawData = $this->request->post("rawData", '', 'trim');
        if (!$code || !$rawData) {
            $this->error("参数不正确");
        }
        $userInfo = (array)json_decode($rawData, true);
        $params = [
            'appid'      => $config['wxappid'],
            'secret'     => $config['wxappsecret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                $platform = 'wxapp';
                $result = [
                    'openid'        => $json['openid'],
                    'userinfo'      => [
                        'nickname' => $userInfo['nickName'],
                    ],
                    'access_token'  => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                ];
                $extend = ['gender' => $userInfo['gender'], 'nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl']];
                $ret = Service::connect($platform, $result, $extend);
                if ($ret) {
                    $auth = Auth::instance();
                    Task::execute_task(2, $auth->getUserinfo()['id']);
                    $this->success("登录成功", ['userInfo' => $auth->getUserinfo()]);
                } else {
                    $this->error("连接失败");
                }
            }
        }

    }

    /*
     * 消息列表
     */
    public function messageList(){
        $user_id = $this->auth->getUserinfo()['id'];
        $where['to_user_id'] = $user_id;

        $messagelist = SelfMessage::where($where)
            ->order('createtime DESC')
            ->paginate()
            ->each(function($item){
                $item->status = 1;
                $item->save();
            })
            ->toArray();

        $this->success('消息列表', $messagelist);  
    }

    /*
     * 更新邀请人信息
     */
    public function invitationUser(){
        $user_id = $this->auth->getUserinfo()['id'];
        $user_top_id = \app\common\model\User::where(array('id'=>$user_id))->value('top_id');
        $top_user_old = \app\common\model\User::where(array('id'=>$user_top_id))->find();
        if($top_user_old){
            $this->error('邀请人信息已存在');   
        }
        $invi_code = input('invi_code/s', '');
        if(!$invi_code){
            $this->error('请填写邀请码');
        }
        $top_user_new = \app\common\model\User::where(array('invi_code'=>$invi_code))->find();
        if(!$top_user_new){
            $this->error('邀请人不存在');
        }
        if($top_user_new['id'] == $user_id){
            $this->error('邀请人不能是自己');
        }

        Db::startTrans();
        $update_user = \app\common\model\User::where(array('id'=>$user_id))->update(array('top_id'=>$top_user_new['id']));
        if($update_user === false){
            Db::rollback();
            $this->error('操作失败');
        }
        $inviData['user_id'] = $top_user_new['id'];
        $inviData['to_user_id'] = $user_id;
        $inviData['createtime'] = time();
        $add_invitation = Db::name('self_invitation')->insertGetId($inviData);
        if(!$add_invitation){
            Db::rollback();
            $this->error('操作失败');
        }
        Db::commit();
        $this->success('操作成功');
    }

    /**
     * 获取邀请码
     */
    public function getInviteImage(){

        try {
            $result = \app\common\service\Invite::createInviteImg($this->auth->getUser());
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        
        $result = cdnurl(str_replace(ROOT_PATH.'public', '', $result), 'https://www.furunkeiji.com/');
        $this->success('ok', [
            'img' => $result.'?t='.date('Y-m-d')
        ]);
    }
}
